<template>
  <div class="fillcontain">
    <div class="user-header-title">
      <div class="left souIpt" ref="search" :model="search">
        <div class="table_container">
          <div class="table_container_header">
            <div class="table_container_header_left">
              <el-button type="primary" icon="el-icon-plus" size="mini" @click="addUserOnClick">添加</el-button>
              <el-button type="success" icon="el-icon-refresh" size="mini" @click="refresh">刷新</el-button>
            </div>
            <div class="table_container_header_right"></div>
          </div>
        </div>
      </div>
    </div>
    <div class="table_container">
      <el-table
        @selection-change="getRowDatas"
        :row-class-name="tableRowClassName"
        :data="tableData"
        style="width:100%"
        height="600"
      >
        <el-table-column type="index" label="序号"  width="50"></el-table-column>
        <el-table-column label="角色名称" prop="rolename" ></el-table-column>
        <el-table-column label="创建时间" prop="createtime" >
          <template slot-scope="scope">{{formateTime(scope.row.createtime)}}</template>
        </el-table-column>
        <el-table-column label="机构" prop="orgid" >
          <template slot-scope="scope">{{getDicMsgById('org',scope.row.orgid)}}</template>
        </el-table-column>
        <el-table-column label="创建者" prop="createuser" >
          <template slot-scope="scope">{{getDicMsgById('User',scope.row.createuser)}}</template>
        </el-table-column>
        <el-table-column label="备注" prop="note" ></el-table-column>
        <el-table-column label="操作" align="center" min-width="200">
          <template slot-scope="scope">
            <div>
              <el-button
                @click="allocationJurisdiction(scope.$index, scope.row)"
                type="success"
                size="mini"
              >分配权限</el-button>
              <el-button
                type="primary"
                @click="updataUserData(scope.$index, scope.row)"
                size="mini"
              >编辑</el-button>
              <el-button
                @click="deletRoleData(scope.$index, scope.row)"
                type="danger"
                size="mini"
              >删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog title="添加角色" :visible.sync="addUserDialogStatus" @close="closeDialog">
        <el-form :model="roleSubObj" label-width="80px">
          <el-form-item label="角色名称:" :label-width="formLabelWidth">
            <el-input v-model="roleSubObj.rolename" placeholder="登录名"></el-input>
          </el-form-item>
          <el-form-item label="备注:" :label-width="formLabelWidth">
            <el-input type="textarea" v-model="roleSubObj.note" placeholder="请输入备注"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addUserDialogStatus = false">取 消</el-button>
          <el-button type="primary" @click.native="addUserSubClick">确 定</el-button>
        </div>
      </el-dialog>

      <el-dialog title="分配权限" :visible.sync="authorityDistribution">
        <el-form :model="selectTable">
          <el-tree
            ref="newTopRightsTree"
            :data="data"
            show-checkbox
            node-key="id"
            :default-checked-keys="defaultCheckID"
            @check="currentChecked"
          ></el-tree>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="authorityDistribution = false">取 消</el-button>
          <el-button type="primary" @click.native="authorityDistributionSub">确 定</el-button>
        </div>
      </el-dialog>

      <div class="paginationWrap right">
        <el-pagination
          v-if="pagination.paginationShow"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="pagination.currentPage"
          :page-sizes="pagination.sizes"
          :page-size="pagination.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.count"
        ></el-pagination>
      </div>
    </div>
  </div>
</template>
<script>
import { get, post } from "../../common/apiconfig";
import { getDicMsgById, formateTime } from "../../common/common";
export default {
  data() {
    return {
      dialogStatus: 0,
      formLabelWidth: "120px",
      activeItem: {},
      DetailList: [],
      defaultCheckID: [],
      activeName: "",
      tableData: [],
      authorityDistribution: false,
      addUserDialogStatus: false,
      orgData: [],
      selectedCategory: [],
      address: {},
      fileList: [],
      xiangQing: {},
      search: {},
      roleSubObj: {},
      rules: {},
      showLoading: false,
      pagination: {
        count: 0,
        size: 10,
        currentPage: 1,
        paginationShow: true
      },
      data: [],
      defaultProps: {
        children: "children",
        label: "label"
      },
      selectTable: {}
    };
  },
  created() {},
  watch: {},
  components: {},
  computed: {},
  mounted() {
    this.getList();
    this.getOrgList();
  },
  methods: {
    getList() {
      let that = this;
      let { currentPage: page, size: rows } = that.pagination;
      post("/RoleList", {
        page,
        rows
      }).then(d => {
        if (d.code == "001") {
          that.tableData = d.data;
          that.pagination.count = d.records;
        } else {
          console.log(d.msg);
        }
      });
    },
    getOrgList() {
      let that = this;
      get("/GetTreeList", {
        TreeType: "Operation"
      }).then(d => {
        if (d.code == "001") {
          that.renderTreeData(d.data.items);
        } else {
          console.log(d.msg);
        }
      });
    },
    addUserOnClick() {
      this.roleSubObj = {};
      this.dialogStatus = 0;
      this.addUserDialogStatus = true;
    },
    authorityDistributionSub() {
      let that = this;
      let { id: RoleID } = this.activeItem;
      let DetailList = this.DetailList.join();
      post("/RoleOperationUpdate", {
        DetailList,
        RoleID
      }).then(d => {
        if (d.code == "001") {
          that.$message.success("修改成功");
          that.authorityDistribution = false;
          that.getList();
        } else {
          console.log(d.msg);
          that.$message.error("修改失败");
        }
      });
    },
    addUserSubClick() {
      let that = this;
      let { rolename: RoleName, id: ID, note: Note } = that.roleSubObj;
      let url = "/RoleNew";
      let errMsg = "添加出错";

      let obj = {
        Note,
        RoleName
      };
      if (this.dialogStatus != 0) {
        errMsg = "修改出错";
        obj.ID = ID;
        url = "/RoleUpdate";
      }
      post(url, obj).then(d => {
        if (d.code == "001") {
          that.dialogStatus = 0;
          that.addUserDialogStatus = false;
          that.$message.success("操作成功");
          that.getList();
        } else {
          console.log(d.msg);
          that.$message.error(errMsg);
        }
      });
    },
    updataUserData(index, item) {
      this.dialogStatus = 1;
      this.addUserDialogStatus = true;
      this.roleSubObj = item;
    },
    deletRoleData(index, item) {
      let that = this;
      let { id: ID } = item;
      this.$confirm("确定要删除该条记录?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          post("/RoleDelete", {
            ID
          }).then(d => {
            if (d.code == "001") {
              that.$message({
                type: "success",
                message: "删除成功!"
              });
              this.getList();
            } else {
              that.$message.error("删除出错！");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    handleSizeChange(val) {
      this.pagination.size = val;
      this.getList();
    },
    handleCurrentChange() {
      this.getList();
    },
    allocationJurisdiction(index, row) {
      this.activeItem = row;
      let that = this;
      let { id: RoleID } = row;
      that.authorityDistribution = true;
      this.$nextTick(() => {
        that.$refs.newTopRightsTree.setCheckedKeys([]);
      });
      get("/RoleOperationList", {
        RoleID
      }).then(d => {
        if (d.code == "001") {
          that.defaultCheckID = d.rows;
          that.DetailList = d.rows;
        } else {
          console.log(d.msg);
        }
      });
    },
    searchList() {},
    getRowDatas(row) {
      console.log(row);
    },
    refresh() {
      this.getList();
    },
    tableRowClassName({ row, rowIndex }) {
      console.log(row);
      if (rowIndex === 1) {
        return "warning-row";
      } else if (rowIndex === 3) {
        return "success-row";
      }
      return "";
    },
    renderTreeData(data) {
      data.forEach(item => {
        item.id = item.ID;
        item.label = item.Name;
      });
      let firstItem = data.filter(item => {
        return item.ID == 0;
      })[0];
      firstItem.children = this.getItemChilren(firstItem.ID, data);
      firstItem.children.forEach(element => {
        element.children = this.getItemChilren(element.ID, data);
      });
      firstItem.children.forEach(element => {
        element.children.forEach(item => {
          item.children = this.getItemChilren(item.ID, data);
        });
      });
      this.data = [firstItem];
    },
    getItemChilren(ID, data) {
      return data.filter(item => {
        return item.ParentID == ID;
      });
    },
    closeDialog() {
      console.log("close");
    },
    currentChecked(nodeObj, SelectedObj) {
      this.DetailList = SelectedObj.checkedKeys;
    },
    formateTime(inputTime) {
      return formateTime(inputTime);
    },
    getDicMsgById(type, id) {
      return getDicMsgById(type, id);
    }
  },

  destroyed() {}
};
</script>

<style scoped >
.table_container {
  padding: 20px;
  max-width: 100vw;
  overflow: auto;
}

.Pagination {
  display: flex;
  justify-content: flex-start;
  margin-top: 8px;
}

.user-header-title {
  overflow: hidden;
  padding-left: 20px;
}

.souIpt .el-input {
  width: 200px;
}

.fillcontain {
  border-radius: 8px;
  padding: 8px;
  background-color: #fff;
}

.table_container_header_left {
  float: left;
  margin-left: -10px;
}

.paginationWrap {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
